package set_;

import java.util.HashSet;
import java.util.Objects;

/**
 * @author DCSGO
 * @version 1.0
 * 定义一个Employee类
 * 该类包含：private成员属性name,age
 * 要求：
 * 1.创建3个Employee放入HashSet中
 * 2.当name和age的值相同时，认为是相同员工
 * 不能添加到HashSet集合中
 */

@SuppressWarnings({"all"})
public class HashSetExercise {
    public static void main(String[] args) {
        //要求我们不能把 name 和 age 同时相同的 Employee 对象放入
        //到 HashSet 中我们只需要重写一下 hashCode 方法和 equals 方法即可
        HashSet hashSet = new HashSet();
        hashSet.add(new Employee("小王", 19));
        hashSet.add(new Employee("老张", 28));
        hashSet.add(new Employee("淑芬", 22));
        hashSet.add(new Employee("老张", 28));
        hashSet.add(new Employee("小王", 23));
        System.out.println(hashSet);
        /*
         * [
         * Employee{name='淑芬', age=22},
         * Employee{name='老张', age=28},
         * Employee{name='小王', age=23},
         * Employee{name='小王', age=19}]
         */
    }
}

class Employee {
    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return age == employee.age && Objects.equals(name, employee.name);
    }

    @Override
    public String toString() {
        return "\nEmployee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
